<template>
  <!-- loading给数据获取添加加载进度条 -->
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 头部根节点 -->
        <treeTools :tree-node="company" :is-root="true" @addDept="addDept" />

        <!-- 内容组织架构 -->
        <!-- data用来展示数据 props表示配置从何处读取数据(若配置为空默认从label和children读取) default-expand-all默认全部展开 -->
        <el-tree :data="departs" :props="defaultProps" default-expand-all>
          <template v-slot="{data}">
            <!-- 标签属性中的驼峰命名可以用小写连字符方式---而且校验工具默认转换小写连字符 -->
            <treeTools :tree-node="data" @delDept="getDepartments" @addDept="addDept" @editDept="editDept" />
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 弹出层组件 -->
    <addDept ref="addDept" :show-dialog.sync="showDialog" :tree-node="treeNode" @closedialog="closedialog" />

  </div>
</template>

<script>
import treeTools from './components/treeTools.vue'
import addDept from './components/addDept.vue'
import { getDepartments } from '@/api/departments'
import { transListToTreeData } from '@/utils'
export default {
  components: {
    treeTools, addDept
  },
  data() {
    return {
      company: {},
      departs: [],
      defaultProps: {
        // 默认label: 'label',children: 'children'
        label: 'name' // 表示 从这个属性显示内容
      },
      showDialog: false, // 显示窗体
      treeNode: null, // 记录选中新增部门的信息
      loading: false// 记录加载进度条
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    // 获取部门信息
    async getDepartments() {
      this.loading = true
      const res = await getDepartments()
      // console.log(res.depts)
      this.company = { name: res.companyName, manager: '负责人', id: '' }// 根节点id传值为'',防止根节点添加部门时获取不到id,undefined
      this.departs = transListToTreeData(res.depts, '')// 根节点的pid为'',以根节点的pid传值
      // setTimeout(() => { this.loading = false }, 500)
      // await总是会等到后面的promise进行reslove
      await new Promise(resolve => setTimeout(() => resolve(), 500))
      this.loading = false
    },
    // 新增部门
    addDept(node) {
      this.showDialog = true
      this.treeNode = node
    },
    // 添加成功关闭弹窗
    closedialog() {
      this.showDialog = false
      // 重新渲染部门信息
      this.getDepartments()
    },
    // 编辑部门
    editDept(node) {
      // 根据当前选中要编辑的部门id查询相关信息--通过调用子组件方法直接给子组件数据
      this.$refs.addDept.getDepartDetail(node.id)
      // 打开弹窗
      this.showDialog = true
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
.dropdown {
  cursor: pointer;
}
</style>
